#include "jtabwidget.h"
#include <QToolButton>
#include <QTabBar>

namespace QTE
{

class Q_DECL_HIDDEN JTabWidgetPrivate : public QObject
{
public:
	explicit JTabWidgetPrivate(JTabWidget *q_ptr);

public:
	void update();

public:
	JTabWidget *q_ptr;
	QToolButton *m_addButton;
	QWidget *m_cCornerWidget = nullptr;
};

JTabWidgetPrivate::JTabWidgetPrivate(JTabWidget *q_ptr) :
	QObject(q_ptr), q_ptr(q_ptr),
	m_addButton(new QToolButton(q_ptr))
{
	m_addButton->setText("+");
}

void JTabWidgetPrivate::update()
{
	int x = 0;
	int y = 0;
	int height = m_addButton->height();

	int count = q_ptr->count();
	auto tabBar = q_ptr->tabBar();

	if( count > 0 )
	{
		height = tabBar->height() - 4;
		y = 2;

		auto cw = q_ptr->cornerWidget(Qt::TopLeftCorner);
		if( cw )
			x += cw->width() + 1;
	}
	m_addButton->setFixedHeight(height);

	for(int i=0; i<count; i++)
		x += tabBar->tabRect(i).width();

	int tabMaxWidth = q_ptr->width() - m_addButton->width();

	if( m_cCornerWidget )
	{
		tabMaxWidth -= m_cCornerWidget->width();

		m_cCornerWidget->move(q_ptr->width() - m_cCornerWidget->width(), y);
		m_cCornerWidget->setFixedHeight(height);
	}

	if( tabMaxWidth < 0 )
		tabMaxWidth = 0;

	if( x > tabMaxWidth )
		x = tabMaxWidth;

	tabBar->setMaximumWidth(tabMaxWidth);
	m_addButton->move(x, y);
}

/*--------------------------------------------------------------------------------------------------------*/

JTabWidget::JTabWidget(QWidget *parent) :
	QTabWidget(parent),
	d_ptr(new JTabWidgetPrivate(this))
{
	connect(d_ptr->m_addButton, &QToolButton::clicked, this, &JTabWidget::addTabRequested);
}

JTabWidget::~JTabWidget()
{

}

QToolButton *JTabWidget::addButton()
{
	return d_ptr->m_addButton;
}

const QToolButton *JTabWidget::addButton() const
{
	return d_ptr->m_addButton;
}

void JTabWidget::setCornerWidget(QWidget *widget, Qt::Corner corner)
{
	Q_ASSERT(widget);

	if( corner != Qt::TopRightCorner )
		return QTabWidget::setCornerWidget(widget, corner);

	if( d_ptr->m_cCornerWidget )
		d_ptr->m_cCornerWidget->deleteLater();

	widget->setParent(this);

	d_ptr->m_cCornerWidget = widget;
	d_ptr->update();
}

QWidget *JTabWidget::cornerWidget(Qt::Corner corner) const
{
	return corner == Qt::TopRightCorner?
				d_ptr->m_cCornerWidget : QTabWidget::cornerWidget(corner);
}

void JTabWidget::showEvent(QShowEvent *event)
{
	QTabWidget::showEvent(event);
	d_ptr->update();
}

void JTabWidget::resizeEvent(QResizeEvent *event)
{
	QTabWidget::resizeEvent(event);
	d_ptr->update();
}

void JTabWidget::tabInserted(int index)
{
	QTabWidget::tabInserted(index);
	d_ptr->update();
}

void JTabWidget::tabRemoved(int index)
{
	QTabWidget::tabRemoved(index);
	d_ptr->update();
}

} //namespace QTE
